package edu.utd.text.game.designer.commands;

import java.util.Scanner;

import edu.utd.text.game.designer.controller.DesignerController;
import edu.utd.text.game.domain.GameMap;
import edu.utd.text.game.domain.areas.Room;
import edu.utd.text.game.domain.exceptions.GameObjectNotFoundException;
import edu.utd.text.game.domain.item.GameItem;

public class DisplayGameItemCommand implements DesignerCommand {
	private String itemName;
	
	public DisplayGameItemCommand() {  }
	
	public DisplayGameItemCommand(String itemName) {
		this.itemName = itemName;
	}
	
	public String execute() throws Exception {
		Scanner scanner = new Scanner(System.in);
		if (null == this.itemName) {
			System.out.println("Name of item to display");
			this.itemName = scanner.nextLine().trim();
		}
		System.out.println("Name of room to look in (default: search all rooms");
		String roomName = scanner.nextLine().trim();
		
		if (roomName.isEmpty() || roomName.equals("")) {
			//search all rooms and return results
			GameMap map = DesignerController.INSTANCE.getGameMap();
			String result = "";
			for (Room room : map.getRooms()) {
				try {
					GameItem itemToDisplay = room.retrieveGameItemByName(this.itemName);
					result += "\n" + formatDisplay(itemToDisplay, room) + "\n";
				} catch (GameObjectNotFoundException gonfx) {
					/* Keep looking */
				}
			}
			if (result.isEmpty() || result.equals("")) {
				return "Item not found: \"" + this.itemName + "\"";
			}
			return result;
		} else {
			//look in the specified room
			Room room = DesignerController.INSTANCE.getGameMap().getRoomByName(roomName);
			if (null == room) {
				return "There is no room named \"" + roomName + "\" in the game map.";
			}
			try {
				GameItem itemToDisplay = room.retrieveGameItemByName(this.itemName);
				return formatDisplay(itemToDisplay, room);
			} catch (GameObjectNotFoundException gonfx) {
				return "No game item named \"" + itemName
					+ "\" was found in the room: \"" + room.getRoomName() + "\".";
			}
		}
	}
	
	private String formatDisplay(GameItem itemToDisplay, Room roomWhereFound) {
		String displayString = "=======================\nNAME: \""
			+ itemToDisplay.getName() + "\"\n=======================\n"
			+ "FOUND IN ROOM: \"" + roomWhereFound.getRoomName()
			+ "\"\n=======================\nITEM TAGS:\n"
			+ itemToDisplay.getTags().toString()
			+ "\n=======================\nITEM DESCRIPTION:\n\""
			+ itemToDisplay.getDescription() + "\"\n=======================";
		return displayString;
	}
}
